'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Admin Template' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// 开发模式有必要用cdn吗？没必要
// 只有打包成正式上线才要
const cdn = {
  css: [],
  js: []
}
// const externals = {

// }

// // 只有当是生产环境时才让它有值
// if (process.env.NODE_ENV == 'production') {
//   cdn = {
//     css: [
//       // 导入css
//       // element-ui css
//       'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // 样式表
//     ],
//     js: [
//       // 导入所有的js
//       // vue must at first!
//       'https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.common.js', // vuejs
//       // element-ui js
//       'https://unpkg.com/element-ui/lib/index.js', // elementUI
//       'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/jszip.min.js',
//       'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/xlsx.full.min.js'
//     ]
//   }

//   externals = {
//     // 左边key代表包名
//     // 右边的value就是它在代码中的使用（根示例）
//     'vue': 'Vue',
//     'element-ui': 'ELEMENT',
//     'xlsx': 'XLSX'
//   }
// }
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,

  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },

    // 设置反向代理
    proxy: {
      // 拦截携带 `/api` 路径的请求
      // 把它的域名切换成 http://localhost:3000,再用代理服务器去访问
      // 所以例如你项目里访问的是： http://localhost:9528/api/sys/login
      // 它就会用代理服务器帮你访问： http://localhost:3000/api/sys/login
      // "/api": {
      //   target: "http://localhost:3000",
      //   changeOrigin: true,
      // }

      // 标记名可以改，例如可以改成 /xx
      // 但是改成/xx后，就意味着你发的请求变成了  http://localhost:9528/xx/sys/login
      // 然后通过反向代理改变域名请求后，也只是变成了 http://localhost:3000/xx/sys/login
      // 这个xx还在，而我们接口没有xx路径，只有api这个路径
      // 所以用 pathRewrite把 /xx 替换成 /api 才行
      // "/xx": {
      //   target: "http://localhost:3000",
      //   changeOrigin: true,
      //   // 路径重写
      //   pathRewrite: {
      //     // 把路径上的/xx 替换成 /api
      //     '^/xx': '/api'
      //   }

      // 公司里常见下面这种写法
      // 原本访问：http://localhost:9528/xx/sys/login
      // 用反向代理后，切换域名变成了http://localhost:3000/api/xx/sys/login
      // 所以需要用 pathRewrite把/xx删掉，也就是替换为''字符串,就变成了
      // http://localhost:3000/api/sys/login
      '/xx': {
        target: 'http://localhost:3000/api',
        changeOrigin: true,
        pathRewrite: {
          '^/xx': ''
        }
      }
    }
  },

  // 专门用来提供写webpack配置的地方
  configureWebpack: {
    // externals: externals,
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  },
  chainWebpack(config) {
    // 使用html插件，运用刚刚声明的cdn变量
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    }),

    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  }
}
